package org.ljdp.bootstrap;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class LoaderUtil {

	public static List<URL> getAllJarUrls(String[] paths) throws MalformedURLException {
		if (null == paths || 0 == paths.length) {
			throw new IllegalArgumentException("Paths cannot be empty .");
		}

		List<URL> urls = new ArrayList<URL>();
		for (String path : paths) {
			getJarUrl(path, urls);
		}

		return urls;
	}

	public static void getJarUrl(String path, List<URL> urls) throws MalformedURLException {
		File jarPath = new File(path);
		recursionFile(jarPath, urls);
	}

	private static void recursionFile(File file, List<URL> jarUrls) throws MalformedURLException {
		if (file.isDirectory()) {

			System.out.println("Loading:"+file.getAbsolutePath());
			jarUrls.add(file.toURI().toURL());

			File[] allJars = file.listFiles();
			for (File childFile : allJars) {

				if (!childFile.isDirectory() && childFile.getName().endsWith(".jar")) {
					if(!childFile.getName().startsWith("ljdp-bootstrap")) {
						System.out.println(childFile.getName());
						jarUrls.add(childFile.toURI().toURL());
					}
				} else {
					recursionFile(childFile, jarUrls);
				}
			}
		}
	}

	public static void addClasses(List<URL> urls)
			throws NoSuchMethodException, IllegalAccessException,
			InvocationTargetException {
		URLClassLoader classloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
		add.setAccessible(true);

		for (URL url : urls) {
			add.invoke(classloader, new Object[] { url });
		}
	}

	public static List<URL> buildJarModelURL(String procPath)
			throws MalformedURLException {
		List<URL> urls = getAllJarUrls(new String[] { procPath + "/lib"});

		urls.add(new File(procPath + "/conf").toURI().toURL());
		return urls;
	}
	
	public static List<URL> buildWebModelURL(String procPath, String webpath)
			throws MalformedURLException {
		String webBasePath = procPath+ "/webapp/"+ webpath;
		
		String libpath = webBasePath + "/WEB-INF/lib";
		List<URL> urls = getAllJarUrls(new String[] {libpath});
		
		String classpath = webBasePath + "/WEB-INF/classes";
		urls.add(new File(classpath).toURI().toURL());
		return urls;
	}

}
